<?php

/**
 * Erra_Core_File - Files and IO handling
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Erra_Core_File {

    public static function spl_scanRecursiveDir($dir, $extension = null, $onlyfiles = true, $fullpath = true) {
        // TODO : change windows flag ?
        if (isset($dir) && is_readable($dir)) {
            $dlist = array();
            $dir = realpath($dir);
            if ($onlyfiles) {
                $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
            } else {
                $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST);
            }

            foreach ($objects as $entry => $object) {
                if (!$fullpath) {
                    $entry = str_replace($dir, '', $entry);
                }
                if (is_null($extension)) {
                    $dlist[] = $entry;
                } else {
                    $extList = (strstr($extension, '|') !== false) ? explode('|', $extension) : array($extension);

                    foreach ($extList as $validExtension) {
                        if (strstr($entry, $validExtension) !== false) {
                            $dlist[] = $entry;
                            break;
                        }
                    }
                }
            }

            return $dlist;
        }
    }

    /**
     * Erra_Core_File::tempnam() - Creates a file with a unique filename, with access permission set to 0600, in the
     * specified directory. If the directory does not exist, tempnam() may generate a file in the system's
     * temporary directory, and return the name of that.
     *
     * @param string $prefix
     * @return
     */
    public static function tempnam($prefix = 'ufm') {
        if (function_exists('sys_get_temp_dir')) {
            $dir = sys_get_temp_dir();
        } else {
            $dir = ini_get('upload_tmp_dir');
        }

        return tempnam($dir, $prefix);
    }

    /**
     * Erra_Core_File::web2path() - Transform filename from webname to server filename
     *
     * @param mixed $file
     * @return
     */
    public static function web2path($file) {
        if (file_exists($file)) {
            return $file;
        }
        $WEBROOT = config_get("application.http_webroot");
        $DOCUMENT_ROOT = DOCUMENT_ROOT . '/' . config_get("path.public_directory");
        $file = str_replace($WEBROOT, $DOCUMENT_ROOT, $file);
        return $file;
    }

    /**
     * Erra_Core_File::size() - Transforms a size according to a particular unit
     *
     * @param mixed $size
     * @param string $unit
     * @return
     */
    public static function size($size, $unit = 'B') {
        $kb = 1024;
        $mb = 1024 * $kb;
        $gb = 1024 * $mb;
        $tb = 1024 * $gb;

        if ($size < $kb) {
            return $size . " " . $unit;
        } else if ($size < $mb) {
            return round($size / $kb, 2) . " K" . $unit;
        } else if ($size < $gb) {
            return round($size / $mb, 2) . " M" . $unit;
        } else if ($size < $tb) {
            return round($size / $gb, 2) . " G" . $unit;
        } else {
            return round($size / $tb, 2) . " T" . $unit;
        }
    }

    /**
     * Erra_Core_File::getExtension()
     *
     * @param mixed $f
     * @return
     */
    public static function getExtension($filename) {
        $filename = explode('.', basename($filename));

        if (count($filename) <= 1) {
            return '';
        }

        return strtolower($filename[count($filename) - 1]);
    }

    public static function deleteDir($dir) {
        $iterator = new RecursiveDirectoryIterator($dir);
        $forbiddenFiles = array('.htaccess', 'robots.txt', 'index.php');
        foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
            if ($file->isDir()) {
                rmdir($file->getPathname());
            } else {
                if (!in_array(basename($file->getPathname()), $forbiddenFiles)) {
                    unlink($file->getPathname());
                }
            }
        }
        rmdir($dir);
    }

    public static function Zip($source, $destination) {
        if (!extension_loaded('zip') || !file_exists($source)) {
            return false;
        }

        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            return false;
        }

        $source = str_replace('\\', '/', realpath($source));

        if (is_dir($source) === true) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

            foreach ($files as $file) {
                $file = str_replace('\\', '/', realpath($file));

                if (is_dir($file) === true) {
                    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                } else if (is_file($file) === true) {
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                }
            }
        } else if (is_file($source) === true) {
            $zip->addFromString(basename($source), file_get_contents($source));
        }

        return $zip->close();
    }

    /* backup the db OR just a table */

    public static function backupTables($fileName, $tables = '*') {
        $link = mysql_connect(config_get('database.db_host'), config_get('database.db_user'), config_get('database.db_pass'));
        mysql_select_db(config_get('database.db_name'), $link);
        //get all of the tables
        if ($tables == '*') {
            $tables = array();
            $result = mysql_query('SHOW TABLES');
            while ($row = mysql_fetch_row($result)) {
                $tables[] = $row[0];
            }
        } else {
            $tables = is_array($tables) ? $tables : explode(',', $tables);
        }

        //cycle through
        foreach ($tables as $table) {
            $result = mysql_query('SELECT * FROM ' . $table);
            $num_fields = mysql_num_fields($result);

            $return.= 'DROP TABLE IF EXISTS ' . $table . ';';
            $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
            $return.= "\n\n" . $row2[1] . ";\n\n";

            for ($i = 0; $i < $num_fields; $i++) {
                while ($row = mysql_fetch_row($result)) {
                    $return.= 'INSERT INTO ' . $table . ' VALUES(';
                    for ($j = 0; $j < $num_fields; $j++) {
                        $row[$j] = addslashes($row[$j]);
                        $row[$j] = preg_replace("#\n#", "\\n", $row[$j]);
                        if (isset($row[$j])) {
                            $return.= '"' . $row[$j] . '"';
                        } else {
                            $return.= '""';
                        }
                        if ($j < ($num_fields - 1)) {
                            $return.= ',';
                        }
                    }
                    $return.= ");\n";
                }
            }
            $return.="\n\n\n";
        }

        //save file
        $handle = fopen($fileName, 'w+');
        fwrite($handle, $return);
        fclose($handle);
    }

}

?>